import React, { useEffect, useLayoutEffect, useMemo, useState } from 'react';
import { debounce } from 'lodash';
import { filterTreeData, findTreeData } from '@/utils/tree';
import { HighlightText } from '@/molecules';
import { Empty, Input, Tree } from 'antd';
import classNames from 'classnames';
import IconFont from '@/components/IconFont';
import styles from './index.less';

const SearchTree = ({ value, onChange, treeData, placeholder = '关键字', className }) => {
    const [keyword, setKeyword] = useState();
    const setKeywordDebounce = useMemo(() => debounce(setKeyword, 500), []);
    // 过滤后的树数据
    const filteredTreeData = useMemo(
        () => filterTreeData(treeData, item => !keyword || item?.name?.indexOf(keyword) > -1),
        [keyword, treeData]
    );
    const [expandedKeys, setExpandedKeys] = useState([]);
    // 动态计算展开的节点
    useEffect(() => {
        if (keyword) {
            const result = [];
            const pickPid = array => {
                array.forEach(item => {
                    if (item.children?.length) {
                        result.push(item.id);
                        pickPid(item.children);
                    }
                });
            };
            pickPid(filteredTreeData);
            setExpandedKeys(result);
        }
    }, [filteredTreeData, keyword]);

    // 第一个节点不允许被折叠
    useLayoutEffect(() => {
        if (expandedKeys?.length === 0 && filteredTreeData?.length) {
            setExpandedKeys([filteredTreeData[0].id]);
        }
    }, [expandedKeys, filteredTreeData]);

    // useEffect(() => {
    //     if (treeData?.length) {
    //         setExpandedKeys([treeData[0].id]);
    //     }
    // }, [treeData]);

    const handleSearchChange = e => {
        setKeywordDebounce(e?.target?.value);
    };

    const handleTreeSelect = keys => {
        if (keys.length) {
            onChange(keys[0], findTreeData(treeData, keys[0]));
        }
    };

    const handleClick = node => {
        if (node.selectable === false) {
            if (expandedKeys.includes(node.id)) {
                setExpandedKeys([...expandedKeys.filter(item => item !== node.id)]);
            } else {
                setExpandedKeys([...expandedKeys, node.id]);
            }
        }
    };

    // 渲染树节点
    const renderTreeNode = nodes =>
        nodes?.map(node => {
            const title = node.disabled ? (
                `${node.name}(审批中)`
            ) : (
                <HighlightText keywords={keyword}>{node.name}</HighlightText>
            );
            return (
                <Tree.TreeNode
                    key={node.id}
                    title={<div onClick={() => handleClick(node)}>{title}</div>}
                    disabled={node.disabled}
                    selectable={node.selectable ?? true}
                >
                    {renderTreeNode(node.children)}
                </Tree.TreeNode>
            );
        });

    return (
        <div className={classNames(className, styles.searchTree)}>
            <div className={classNames('search', styles.search)}>
                <Input
                    placeholder={placeholder}
                    suffix={
                        <IconFont
                            icon="iconoa_top_bnt_search_normal"
                            style={{ fontSize: 16, color: 'rgba(0,0,0,0.45)' }}
                        />
                    }
                    allowClear
                    onChange={handleSearchChange}
                />
            </div>
            <div className={classNames('tree', styles.tree)}>
                {filteredTreeData?.length ? (
                    <Tree
                        onExpand={setExpandedKeys}
                        expandedKeys={expandedKeys}
                        autoExpandParent={false}
                        selectedKeys={[value]}
                        onSelect={handleTreeSelect}
                    >
                        {renderTreeNode(filteredTreeData)}
                    </Tree>
                ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
            </div>
        </div>
    );
};

SearchTree.displayName = 'SearchTree';

export default SearchTree;
